package cn.sxt.logistics.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.sxt.logistics.pojo.User;
import cn.sxt.logistics.pojo.UserExample;
import cn.sxt.logistics.pojo.UserExample.Criteria;
import cn.sxt.logistics.service.PermissionService;
import cn.sxt.logistics.service.UserService;

public class CustomReaml extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	
	@Autowired
	private PermissionService permissionService;
	
	//认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 获取token（表单提交的账号）的身份
		String username = (String) token.getPrincipal();
		
		//从数据库中根据账号查询是否存在此用户
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<User> users = null;
		try {
			users = userService.selectByExample(example );
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		//账号数据库中不存在，直接返回null，Shiro底层抛：org.apache.shiro.authc.UnknownAccountException
		if(users.size() == 0) {
			return null;
		}
		
		User user = users.get(0);
		
		System.out.println("user :"+user);
		//User [userId=1, username=admin, realname=小敬哥, password=41838d33ba36a8f53c1813c219239120, salt=da346, status=1, createDate=Tue Jul 16 00:00:00 CST 2019, roleId=1, rolename=超级管理员, permissionIds=49,1,69,13,15,16,17,11,68,18,20,70,12,22,23,24,25,58,31,35,32,33,34,54,55,57,61,60,59,63,10,36,3]
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
		
		return new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt , this.getName());		
	}

	// 授权方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//获取主身份
		User user = (User) principals.getPrimaryPrincipal();
		System.out.println(user);
		//将当前认证的身份（用户）的角色的权限id切割成数组
		String[] permissionIdsArr = user.getPermissionIds().split(",");
		List<Long> permissionIdsList = new ArrayList<Long>();
		for (String permissionId : permissionIdsArr) {
			permissionIdsList.add(Long.valueOf(permissionId));
		}
		List<String> permissions = permissionService.selectExpressionByIds(permissionIdsList);
		
		//[admin:adminPage, system:systemManager, role:rolePage, permission:permissionPage, admin:list, admin:insert, admin:delete, admin:update, role:insert, role:update]
		//创建授权信息对象
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//将身份的角色设置Shiro
		authorizationInfo.addRole(user.getRolename());
		
		//将权限表达式设置给Shiro
		authorizationInfo.addStringPermissions(permissions);
		
		return authorizationInfo;
	}

}
